import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { ArrowLeft, TrendingUp, Calendar, Target, Clock, BarChart3, PieChart, Tag, Brain } from 'lucide-react'
import LoadingSpinner from '../components/LoadingSpinner'
import { statsAPI } from '../services/api'
import { insightsAPI } from '../services/insightsAPI'
import type { WorkPatterns, ProductivitySuggestions, DataStatus } from '../services/insightsAPI'
import { getCategoryLabel } from '../utils'
import TimeTrendsChart from '../components/charts/TimeTrendsChart'
import CategoryPieChart from '../components/charts/CategoryPieChart'
import PriorityBarChart from '../components/charts/PriorityBarChart'
import CompletionRateChart from '../components/charts/CompletionRateChart'
// import EfficiencyRadarChart from '../components/charts/EfficiencyRadarChart'
import EfficiencyMetricsChart from '../components/charts/EfficiencyMetricsChart'
import WorkPatternsChart from '../components/insights/WorkPatternsChart'
import ProductivitySuggestionsComponent from '../components/insights/ProductivitySuggestions'
import DataRequirements from '../components/insights/DataRequirements'

interface StatsOverview {
  totalTasks: number
  completedTasks: number
  pendingTasks: number
  overdueTasks: number
  completionRate: number
  overdueRate: number
}

interface CategoryStats {
  category: string
  total: number
  completed: number
  pending: number
  completionRate: number
}

interface PriorityStats {
  priority: string
  total: number
  completed: number
  pending: number
  completionRate: number
}

interface TimeTrend {
  date: string
  created: number
  completed: number
}

interface EfficiencyStats {
  avgCompletionDays: number
  delayRate: number
  categoryEfficiency: Array<{
    category: string
    avgDays: number
    completedCount: number
  }>
  totalCompletedTasks: number
}

interface TagUsage {
  tag: string
  count: number
}

export default function StatsPage() {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(true)
  const [selectedPeriod, setSelectedPeriod] = useState(7)
  const [activeTab, setActiveTab] = useState<'basic' | 'insights'>('basic')
  
  // 基础统计数据状态
  const [overview, setOverview] = useState<StatsOverview | null>(null)
  const [categoryStats, setCategoryStats] = useState<CategoryStats[]>([])
  const [priorityStats, setPriorityStats] = useState<PriorityStats[]>([])
  const [timeTrends, setTimeTrends] = useState<TimeTrend[]>([])
  const [efficiency, setEfficiency] = useState<EfficiencyStats | null>(null)
  const [tagUsage, setTagUsage] = useState<TagUsage[]>([])
  
  // 智能洞察数据状态
  const [workPatterns, setWorkPatterns] = useState<WorkPatterns | null>(null)
  const [productivitySuggestions, setProductivitySuggestions] = useState<ProductivitySuggestions | null>(null)
  const [dataStatus, setDataStatus] = useState<DataStatus | null>(null)
  const [insightsLoading, setInsightsLoading] = useState(false)

  useEffect(() => {
    loadAllStats()
  }, [selectedPeriod])

  useEffect(() => {
    if (activeTab === 'insights' && !dataStatus) {
      loadInsights()
    }
  }, [activeTab, dataStatus])

  const loadAllStats = async () => {
    try {
      setLoading(true)
      
      const [
        overviewResult,
        categoryResult,
        priorityResult,
        trendsResult,
        efficiencyResult,
        tagResult
      ] = await Promise.all([
        statsAPI.getOverview(),
        statsAPI.getCategoryDistribution(),
        statsAPI.getPriorityDistribution(),
        statsAPI.getTimeTrends(selectedPeriod),
        statsAPI.getEfficiency(),
        statsAPI.getTagUsage()
      ])

      console.log('📊 前端统计数据加载结果:')
      console.log('概览数据:', overviewResult)
      console.log('分类数据:', categoryResult)
      console.log('优先级数据:', priorityResult)
      console.log('趋势数据:', trendsResult)
      console.log('效率数据:', efficiencyResult)
      console.log('标签数据:', tagResult)
      
      if (overviewResult.success) setOverview(overviewResult.data)
      if (categoryResult.success) setCategoryStats(categoryResult.data)
      if (priorityResult.success) setPriorityStats(priorityResult.data)
      if (trendsResult.success) {
        console.log('📊 设置趋势数据:', trendsResult.data.trends)
        setTimeTrends(trendsResult.data.trends)
      }
      if (efficiencyResult.success) setEfficiency(efficiencyResult.data)
      if (tagResult.success) setTagUsage(tagResult.data)
      
    } catch (error) {
      console.error('加载统计数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const loadInsights = async () => {
    try {
      setInsightsLoading(true)
      
      // 首先获取数据状态
      const dataStatusResult = await insightsAPI.getDataStatus()
      setDataStatus(dataStatusResult)
      
      // 如果数据充足，则加载洞察内容
      if (dataStatusResult.readiness.overall) {
        const [
          workPatternsResult,
          suggestionsResult
        ] = await Promise.all([
          insightsAPI.getWorkPatterns(),
          insightsAPI.getProductivitySuggestions()
        ])

        setWorkPatterns(workPatternsResult)
        setProductivitySuggestions(suggestionsResult)
      }
      
    } catch (error) {
      console.error('加载智能洞察失败:', error)
    } finally {
      setInsightsLoading(false)
    }
  }

  if (loading) {
    return <LoadingSpinner size="lg" text="加载统计数据中..." fullScreen />
  }

  return (
    <div className="min-h-screen bg-theme-bg-secondary">
      {/* 头部 */}
      <div className="sticky top-0 z-10 bg-theme-bg/95 backdrop-blur-sm border-b border-theme-border/60 shadow-sm">
        <div className="flex items-center px-4 sm:px-6 py-4">
          <button
            onClick={() => navigate('/')}
            className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all mr-3 touch-manipulation"
          >
            <ArrowLeft size={20} />
          </button>
          <h1 className="text-lg font-semibold text-theme-text">数据统计</h1>
        </div>
      </div>

      <div className="px-4 sm:px-6 pb-6 space-y-4">
        {/* 标签页切换 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 shadow-sm p-2">
          <div className="flex space-x-1">
            <button
              onClick={() => setActiveTab('basic')}
              className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-medium transition-all ${
                activeTab === 'basic'
                  ? 'bg-blue-500 text-white shadow-sm'
                  : 'text-theme-text-secondary hover:bg-theme-bg-secondary'
              }`}
            >
              <BarChart3 size={18} />
              基础统计
            </button>
            <button
              onClick={() => setActiveTab('insights')}
              className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-medium transition-all ${
                activeTab === 'insights'
                  ? 'bg-purple-500 text-white shadow-sm'
                  : 'text-theme-text-secondary hover:bg-theme-bg-secondary'
              }`}
            >
              <Brain size={18} />
              智能洞察
            </button>
          </div>
        </div>
        {/* 内容区域 */}
        {activeTab === 'basic' ? (
          <>
            {/* 概览卡片 */}
            {overview && (
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="bg-theme-bg rounded-2xl p-5 border border-theme-border/60 shadow-sm">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-theme-text-muted font-medium">总任务数</p>
                  <p className="text-2xl font-bold text-theme-text mt-1">{overview.totalTasks}</p>
                </div>
                <div className="p-3 bg-blue-50 rounded-xl border border-blue-100">
                  <BarChart3 size={20} className="text-blue-600" />
                </div>
              </div>
            </div>

            <div className="bg-theme-bg rounded-2xl p-5 border border-theme-border/60 shadow-sm">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-theme-text-muted font-medium">完成率</p>
                  <p className="text-2xl font-bold text-green-600 mt-1">{overview.completionRate}%</p>
                </div>
                <div className="p-3 bg-green-50 rounded-xl border border-green-100">
                  <Target size={20} className="text-green-600" />
                </div>
              </div>
            </div>

            <div className="bg-theme-bg rounded-2xl p-5 border border-theme-border/60 shadow-sm">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-theme-text-muted font-medium">待办任务</p>
                  <p className="text-2xl font-bold text-orange-600 mt-1">{overview.pendingTasks}</p>
                </div>
                <div className="p-3 bg-orange-50 rounded-xl border border-orange-100">
                  <Clock size={20} className="text-orange-600" />
                </div>
              </div>
            </div>

            <div className="bg-theme-bg rounded-2xl p-5 border border-theme-border/60 shadow-sm">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-theme-text-muted font-medium">逾期率</p>
                  <p className="text-2xl font-bold text-red-600 mt-1">{overview.overdueRate}%</p>
                </div>
                <div className="p-3 bg-red-50 rounded-xl border border-red-100">
                  <TrendingUp size={20} className="text-red-600" />
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 时间趋势图表 */}
        <div className="bg-theme-bg rounded-2xl p-5 border border-theme-border/60 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-sm font-semibold text-theme-text flex items-center gap-2">
              <div className="w-1 h-4 bg-blue-500 rounded-full"></div>
              <Calendar size={16} className="text-theme-text-muted" />
              任务趋势
            </h2>
            <div className="flex gap-1">
              {[7, 14, 30].map(days => (
                <button
                  key={days}
                  onClick={() => setSelectedPeriod(days)}
                  className={`px-3 py-1.5 text-xs font-medium rounded-lg transition-all ${
                    selectedPeriod === days
                      ? 'bg-blue-500 text-white shadow-sm'
                      : 'bg-theme-bg-secondary text-theme-text-secondary hover:bg-blue-50 hover:text-blue-700 border border-theme-border'
                  }`}
                >
                  {days}天
                </button>
              ))}
            </div>
          </div>
          
          <TimeTrendsChart data={timeTrends} selectedPeriod={selectedPeriod} />
        </div>

        {/* 分类分布与完成率 */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
          {/* 分类分布饼图 */}
          <div className="bg-theme-bg rounded-2xl p-5 border border-theme-border/60 shadow-sm">
            <h2 className="text-sm font-semibold text-theme-text mb-4 flex items-center gap-2">
              <div className="w-1 h-4 bg-green-500 rounded-full"></div>
              <PieChart size={16} className="text-theme-text-muted" />
              分类分布
            </h2>
            <CategoryPieChart data={categoryStats} />
          </div>

          {/* 完成率环形图 */}
          {overview && (
            <div className="bg-theme-bg rounded-2xl p-5 border border-theme-border/60 shadow-sm">
              <h2 className="text-sm font-semibold text-theme-text mb-4 flex items-center gap-2">
                <div className="w-1 h-4 bg-emerald-500 rounded-full"></div>
                <Target size={16} className="text-theme-text-muted" />
                整体完成率
              </h2>
              <CompletionRateChart 
                completionRate={overview.completionRate}
                totalTasks={overview.totalTasks}
                completedTasks={overview.completedTasks}
              />
            </div>
          )}
        </div>

        {/* 优先级分布柱状图 */}
        <div className="bg-theme-bg rounded-2xl p-5 border border-theme-border/60 shadow-sm">
          <h2 className="text-sm font-semibold text-theme-text mb-4 flex items-center gap-2">
            <div className="w-1 h-4 bg-purple-500 rounded-full"></div>
            <BarChart3 size={16} className="text-theme-text-muted" />
            优先级分布
          </h2>
          <PriorityBarChart data={priorityStats} />
        </div>

        {/* 效率分析 */}
        {efficiency && (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
            {/* 效率指标 */}
            <div className="bg-theme-bg rounded-2xl p-5 border border-theme-border/60 shadow-sm">
              <h2 className="text-sm font-semibold text-theme-text mb-4 flex items-center gap-2">
                <div className="w-1 h-4 bg-indigo-500 rounded-full"></div>
                <TrendingUp size={16} className="text-theme-text-muted" />
                效率指标
              </h2>
              
              <div className="space-y-4">
                <div className="text-center p-4 bg-blue-50 border border-blue-200 rounded-xl">
                  <p className="text-2xl font-bold text-blue-600">
                    {efficiency.avgCompletionDays !== null ? efficiency.avgCompletionDays : '暂无数据'}
                  </p>
                  <p className="text-sm text-theme-text-secondary font-medium">平均完成天数</p>
                </div>
                <div className="text-center p-4 bg-red-50 border border-red-200 rounded-xl">
                  <p className="text-2xl font-bold text-red-600">{efficiency.delayRate}%</p>
                  <p className="text-sm text-theme-text-secondary font-medium">拖延率</p>
                </div>
                <div className="text-center p-4 bg-green-50 border border-green-200 rounded-xl">
                  <p className="text-2xl font-bold text-green-600">{efficiency.totalCompletedTasks}</p>
                  <p className="text-sm text-theme-text-secondary font-medium">已完成任务</p>
                </div>
              </div>
            </div>

            {/* 效率指标图表 */}
            <div className="bg-theme-bg rounded-2xl p-5 border border-theme-border/60 shadow-sm">
              <h2 className="text-sm font-semibold text-theme-text mb-4 flex items-center gap-2">
                <div className="w-1 h-4 bg-violet-500 rounded-full"></div>
                <Target size={16} className="text-theme-text-muted" />
                分类效率排行
              </h2>
              <EfficiencyMetricsChart data={efficiency} />
            </div>

            {/* 效率排行 */}
            {efficiency.categoryEfficiency.length > 0 && (
              <div className="bg-theme-bg rounded-2xl p-5 border border-theme-border/60 shadow-sm">
                <h2 className="text-sm font-semibold text-theme-text mb-4 flex items-center gap-2">
                  <div className="w-1 h-4 bg-amber-500 rounded-full"></div>
                  <BarChart3 size={16} className="text-theme-text-muted" />
                  效率排行
                </h2>
                <div className="space-y-2">
                  {efficiency.categoryEfficiency.map((cat, index) => (
                    <div key={cat.category} className="flex items-center justify-between p-3 bg-theme-bg-secondary border border-theme-border rounded-xl">
                      <div className="flex items-center gap-3">
                        <span className={`text-xs px-2 py-1 rounded-full font-medium ${
                          index === 0 ? 'bg-yellow-500 text-white' :
                          index === 1 ? 'bg-slate-400 text-white' :
                          index === 2 ? 'bg-amber-600 text-white' :
                          'bg-slate-200 text-theme-text-secondary'
                        }`}>
                          #{index + 1}
                        </span>
                        <span className="text-sm font-medium text-theme-text">
                          {getCategoryLabel(cat.category)}
                        </span>
                      </div>
                      <div className="text-xs text-theme-text-secondary">
                        平均 {cat.avgDays !== null ? `${cat.avgDays} 天` : '暂无数据'} ({cat.completedCount} 个)
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}

        {/* 标签使用统计 */}
        {tagUsage.length > 0 && (
          <div className="bg-theme-bg rounded-2xl p-5 border border-theme-border/60 shadow-sm">
            <h2 className="text-sm font-semibold text-theme-text mb-4 flex items-center gap-2">
              <div className="w-1 h-4 bg-orange-500 rounded-full"></div>
              <Tag size={16} className="text-theme-text-muted" />
              热门标签
            </h2>
            
            <div className="flex flex-wrap gap-2">
              {tagUsage.map(tag => (
                <div
                  key={tag.tag}
                  className="flex items-center gap-2 px-3 py-2 bg-theme-bg-secondary border border-theme-border rounded-full text-sm hover:bg-blue-50 hover:border-blue-200 transition-colors"
                >
                  <span className="text-theme-text font-medium">{tag.tag}</span>
                  <span className="text-xs text-theme-text-secondary bg-theme-bg px-2 py-1 rounded-full border border-theme-border font-semibold">
                    {tag.count}
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}
        </>
        ) : (
          /* 智能洞察内容 */
          <div className="space-y-4">
            {insightsLoading ? (
              <div className="bg-theme-bg rounded-2xl border border-theme-border/60 shadow-sm p-8">
                <div className="text-center">
                  <div className="w-12 h-12 border-3 border-purple-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                  <p className="text-theme-text-secondary font-medium">加载智能洞察中...</p>
                </div>
              </div>
            ) : (
              <>
                {/* 数据充足时显示洞察内容 */}
                {dataStatus?.readiness.overall ? (
                  <>
                    {/* 生产力建议 */}
                    {productivitySuggestions && (
                      <ProductivitySuggestionsComponent data={productivitySuggestions} />
                    )}

                    {/* 工作模式分析 */}
                    {workPatterns && (
                      <div className="bg-theme-bg rounded-2xl border border-theme-border/60 shadow-sm p-5">
                        <h2 className="text-sm font-semibold text-theme-text mb-4 flex items-center gap-2">
                          <div className="w-1 h-4 bg-blue-500 rounded-full"></div>
                          <Brain size={16} className="text-theme-text-muted" />
                          工作模式分析
                        </h2>
                        <WorkPatternsChart data={workPatterns} />
                      </div>
                    )}
                  </>
                ) : (
                  /* 数据不足时显示要求说明 */
                  <DataRequirements 
                    currentDataStatus={dataStatus ? {
                      totalTasks: dataStatus.totalTasks,
                      completedTasks: dataStatus.completedTasks,
                      tasksLast30Days: dataStatus.tasksLast30Days,
                      tasksLast60Days: dataStatus.tasksLast60Days,
                      categoriesWithData: dataStatus.categoriesWithData,
                      prioritiesWithData: dataStatus.prioritiesWithData
                    } : undefined}
                  />
                )}
              </>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
